package com.nuoniu.sibanyun.service.crm.call.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallBaseSetting;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallBaseSettingInfo;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallBaseSettingSearchDto;
import com.nuoniu.sibanyun.entity.expenses.ExpensesBusinessOrder;
import com.nuoniu.sibanyun.mapper.crm.call.CrmCallBaseSettingMapper;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallAgentStatisticsService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallBaseSettingInfoService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallBaseSettingService;
import com.nuoniu.sibanyun.service.expenses.IExpensesBusinessOrderService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 客户管理-外呼套餐 服务实现类
 * </p>
 *
 * @author 白强
 * @since 2022-04-28
 */
@Service
public class CrmCallBaseSettingServiceImpl extends ServiceImpl<CrmCallBaseSettingMapper, CrmCallBaseSetting> implements ICrmCallBaseSettingService {

    @Autowired
    @Lazy
    private IExpensesBusinessOrderService businessOrderService;
    @Autowired
    private ICrmCallBaseSettingInfoService callBaseSettingInfoService;
    @Autowired
    private ICrmCallAgentStatisticsService agentStatisticsService;


    @Override
    public Page<CrmCallBaseSetting> pageCrmCallBaseSetting(CrmCallBaseSettingSearchDto crmCallBaseSettingSearchDto) {
        QueryWrapper<CrmCallBaseSetting> queryWrapper = new QueryWrapper<>();
        String name = crmCallBaseSettingSearchDto.getName();
        Integer status = crmCallBaseSettingSearchDto.getStatus();
        if(StringUtils.isNotBlank(name)){
            queryWrapper.like("name",name);
        }
        if(null != status){
            queryWrapper.eq("status",status);
        }
        return page(crmCallBaseSettingSearchDto.getPage(),queryWrapper);
    }

    @Override
    public void saveCrmCallBaseSetting(CrmCallBaseSetting crmCallBaseSetting) {
        Long id = crmCallBaseSetting.getId();
        String name = crmCallBaseSetting.getName();
        if(checkName(name,id)) {
            throw new NuoNiuException("套餐名称重复");
        }
        if(null != id){
            CrmCallBaseSetting oldCallBaseSetting = getById(id);
            Integer status = oldCallBaseSetting.getStatus();
            if(status > 0) {
                throw new NuoNiuException("套餐已经启用，不能修改");
            }
        }else{
            crmCallBaseSetting.setStatus(0);
        }
        saveOrUpdate(crmCallBaseSetting);

    }

    @Override
    public boolean checkName(String name, Long oldId) {
        QueryWrapper<CrmCallBaseSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        if(null != oldId){
            queryWrapper.ne("id",oldId);
        }
        return count(queryWrapper) > 0;
    }

    /**
     * 批量删除 坐席(超级管理员) 逻辑删除
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        if(null == ids || ids.size() == 0) {
            throw new NuoNiuException("参数错误");
        }
        int checkStatus = batchCheckStatus(ids, 0);
        if(checkStatus != ids.size()) {
            throw new NuoNiuException("套餐已启用，不能删除");
        }
        QueryWrapper<CrmCallBaseSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        remove(queryWrapper);
    }

    @Override
    public void batchEnable(List<Long> ids) {
        if(null == ids || ids.size() == 0) {
            throw new NuoNiuException("参数错误");
        }
        batchUpdateStatus(ids,1);
    }

    @Override
    public void batchDisable(List<Long> ids) {
        if(null == ids || ids.size() == 0) {
            throw new NuoNiuException("参数错误");
        }
        int checkStatus = batchCheckStatus(ids, 0);
        if(checkStatus > 0) {
            throw new NuoNiuException("还未启用，不能暂停");
        }
        batchUpdateStatus(ids,2);
    }

    @Override
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        if(null == ids || ids.size() == 0 || null == status) {
            throw new NuoNiuException("参数错误");
        }
        UpdateWrapper<CrmCallBaseSetting> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        updateWrapper.set("status",status);
        update(updateWrapper);
    }

    @Override
    public int batchCheckStatus(List<Long> ids, Integer status) {
        if(null == ids || ids.size() == 0) {
            throw new NuoNiuException("参数错误");
        }
        QueryWrapper<CrmCallBaseSetting> queryWrapper = new QueryWrapper<>();
        if(null != status){
            queryWrapper.eq("status",status);
        }
        queryWrapper.in("id",ids);
        int count = count(queryWrapper);
        return count;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveBaseSettingOrder(Long baseSettingId) {
//        if( null == baseSettingId )throw new NuoNiuException("参数错误");
//        UserInfo userInfo = UserThreadLocal.get();
//        Integer companyId = userInfo.getCompanyId();
//        LocalDateTime now = LocalDateTime.now();
//        CrmCallBaseSetting baseSetting = this.getById(baseSettingId);
//        if(null == baseSetting)throw new NuoNiuException("套餐信息错误");
//        /** 1.校验 是否有效坐席 */
//        /** 2.校验 套餐是否到期*/
//        CrmCallBaseSettingInfo baseSettingInfo = callBaseSettingInfoService.getByCompany(companyId);
//        if(null != baseSettingInfo){
//            LocalDateTime endTime = baseSettingInfo.getEndTime();
//            if(endTime.compareTo(now) > 0)throw new NuoNiuException("套餐还未到期");
//        }
//
//        /** 2.组装业务订单*/
//        ExpensesBusinessOrder businessOrder = new ExpensesBusinessOrder();
//        Integer type = 1;  //默认 新购
//        if( null != baseSettingInfo &&  !baseSettingInfo.getBaseSettingId().equals(baseSettingId)) {
//            type = 3; //变更
//        }
//        businessOrder.setOrderType(type);
//        businessOrder.setCreateTime(now);
//        businessOrder.setCreateUserId(userInfo.getUserId());
//        businessOrder.setCreateUserName(userInfo.getRealName());
//        businessOrder.setPayTime(now);
//        businessOrder.setPayUserId(userInfo.getUserId());
//        businessOrder.setPayUserName(userInfo.getUserName());
//        businessOrder.setBusinessType(1);
//        businessOrder.setProductionType("callSetting");
//        businessOrder.setProductionId(baseSettingId.intValue());
//        businessOrder.setProductionName(baseSetting.getName());
//        businessOrder.setOrderAmount(baseSetting.getBaseCharges());
//        businessOrder.setPaymentType(2);  //资费类型 1.包年 2.包月 3.一次性
//        businessOrder.setTimeUnit("月");
//        businessOrder.setTimeNumber(1);
//        businessOrder.setPrice(BigDecimal.ZERO);
//        businessOrder.setRenewalType(2);
//        businessOrder.setStatus(3);
//        businessOrder.setProductionSpecifications(JSON.toJSONString(baseSetting));
//        businessOrderService.addBusinessOrder(businessOrder);
    }

}
